package com.spring.demo12.eg1;

import com.spring.demo12.processing.EventListener;
import com.spring.demo12.processing.EventMulticaster;
import com.spring.demo12.processing.SimpleEventMulticaster;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * @author vhans
 */
@Configuration
@ComponentScan
public class MainConfig0 {

    /**
     * 注入事件发布者
     *
     * @param eventListeners 事件监听器
     * @return 事件发布者
     */
    @Bean
    @Autowired(required = false)
    public EventMulticaster eventMulticaster(List<EventListener> eventListeners) {
        EventMulticaster eventMulticaster = new SimpleEventMulticaster();
        if (eventListeners != null) {
            // 加入所有事件监听器
            eventListeners.forEach(eventMulticaster::addEventListener);
        }
        return eventMulticaster;
    }

    /**
     * 注入用户注册服务
     *
     * @param eventMulticaster 事件发布器
     * @return 用户注册服务
     */
    @Bean
    public UserRegisterService userRegisterService(EventMulticaster eventMulticaster) {
        UserRegisterService userRegisterService = new UserRegisterService();
        userRegisterService.setEventMulticaster(eventMulticaster);
        return userRegisterService;
    }
}
